import pytest
import time
import requests
import pymysql
from lib.re_config import CONFIG
from lib.mysql_client import MysqlClient
from lib.request_client import RequestClient
from lib.login_client import LoginClient

# 测试夹具
@pytest.fixture
def register_and_delete():
    # setup
    Logger = LoginClient()
    Logger.debug('== setup 部分 ==')
    case_url = CONFIG['base']['base_url']
    Logger.debug(f"请求头地址:{CONFIG['base']['base_url']}")
    case_path = '/register/'
    Logger.debug(f"请求头端口:{case_path}")
    method = 'POST'
    Logger.debug(f"请求头方法:{method}")
    name_ = 'root_' + str(time.time())
    Logger.debug(f"测试账号名称:{name_}")
    password_ = '123456'
    Logger.debug(f"测试账号密码:{password_}")
    data = {
        'name': name_,
        'password1': password_,
        'password2': password_
    }

    requests.request(method=method, url=case_url + case_path, json=data)
    yield name_,password_
    # teardown 部分
    # 简易写法
    mysql_client = MysqlClient()
    Logger.info('== teardown 部分 ==')
    # 删除语句中，如果 where 条件后的数据名称 name_ 不存在也不会报错
    Logger.debug(f"删除{name_}账号数据")
    sql = [
        f'DELETE from auth_user where username = "{name_}";',
        f'DELETE from user_profile where name = "{name_}";'
    ]
    mysql_client.client(sql)

    # 等价于上面的简易写法
    # with pymysql.connect(host='192.168.58.235', user='root', password='Ceniu2023!', port=3306,
    #                      database='wms') as py_connect:
    #     # 创建游标
    #     with py_connect.cursor() as py_cursor:
    #         # 创建 sql 语句
    #         sql = f'DELETE from auth_user where username = "{name_}";'
    #         ret = py_cursor.execute(sql)
    #         assert ret == 1
    #         sql = f'DELETE from user_profile where name = "{name_}";'
    #         py_cursor.execute(sql)
    #         assert ret == 1
    #         py_connect.commit()


@pytest.fixture
def shou_huo_fixture():
    # setup 部分
    request_client = RequestClient()
    case_path = '/register/'
    method = 'POST'
    name_ = 'root_' + str(time.time())
    password_ = '123456'
    data = {
        'name': name_,
        'password1': password_,
        'password2': password_
    }

    r = request_client.request_(path = case_path, method=method,json=data)
    headers = {
        'token':r.json()['data']['openid'],
        'operator':str(r.json()['data']['user_id'])
    }
    request_client.updates(headers)

    yield request_client,name_,password_
    # teardown 部分
